from rest_framework import serializers

from tsukkomis.models import Tsukkomi, Comment
from users.models import User


class TsukkomiListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tsukkomi
        fields = ("id","like_times","content","create_time")


class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ["id", "username", "head_portrait"]

class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    user = UserSerializer(read_only=True)
    class Meta:
        model = Comment
        fields = ("comment_like_times", "comment_content", "id", "user")

class TsukkomiSerialzer(serializers.ModelSerializer):
    """
    吐槽详情序列化器
    嵌套评论序列化器
    """
    user = UserSerializer(read_only=True)
    comment = CommentSerializer(many=True)

    class Meta:
        model = Tsukkomi
        fields = ("id", "user", "content", "like_times", "share_times", "comment_times","comment")


class PostTsukkimiSerializer(serializers.ModelSerializer):

    class Meta:
        model = Tsukkomi
        fields = ['id', 'content', 'user']

        def validate(self, attrs):
            try:
                user = self.context['request'].user
            except Exception:
                raise serializers.ValidationError("用户不存在")
            attrs['user'] = user
            return attrs


class TsukkomiLikeserizlizer(serializers.ModelSerializer):

    class Meta:
        model = Tsukkomi
        fields = ['id', 'content', 'user']

        def validate(self, attrs):
            try:
                user = self.context['request'].user
            except Exception:
                raise serializers.ValidationError("用户不存在")
            attrs['user'] = user
            return attrs






